package com.pig4cloud.pig.ads.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.pig4cloud.pig.ads.service.AdOperateMaterialService;
import com.pig4cloud.pig.api.entity.AdOperateMaterialDO;
import com.pig4cloud.pig.api.vo.AdOperateMaterialVO;
import com.pig4cloud.pig.api.vo.AdOperateMaterialVO.*;
import com.pig4cloud.pig.api.vo.PushIconVO;
import com.pig4cloud.pig.common.core.util.ECollectionUtil;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.awt.image.ImageFormatException;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

/**
 * 运营素材管理Controller
 *
 * @Title com.pig4cloud.pigx.ads.controller.AdOperateMaterialController.java
 * @Package com.pig4cloud.pigx.ads.controller
 * @Author 马嘉祺
 * @Date 2021/6/17 19:17
 * @Description
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/adopemat")
@Api(value = "adopemat", tags = "运营素材管理")
public class AdOperateMaterialController {

	private final AdOperateMaterialService adOperateMaterialService;

	/**
	 * 运营素材列表
	 *
	 * @param aom
	 * @return
	 */
	@SysLog("运营素材列表")
	@PostMapping("/list")
	public R<List<AdOperateMaterialDO>> list(@RequestBody @Validated AdOperateMaterialVO aom) {
		List<AdOperateMaterialDO> list = adOperateMaterialService.materialList(aom);
		return R.ok(list);
	}

	/**
	 * 运营素材分页列表
	 *
	 * @param aom
	 * @return
	 */
	@SysLog("运营素材分页列表")
	@PostMapping("/listPage")
	public R<IPage<AdOperateMaterialDO>> listPage(@RequestBody @Validated AdOperateMaterialVO aom) {
		IPage<AdOperateMaterialDO> page = adOperateMaterialService.materialPage(aom, aom);
		return R.ok(page);
	}

	/**
	 * 根据主键获取运营素材信息
	 *
	 * @param materialId
	 * @return
	 */
	@SysLog("运营素材信息")
	@GetMapping("/get")
	public R<AdOperateMaterialDO> getMaterial(@RequestParam Long materialId) {
		AdOperateMaterialDO material = adOperateMaterialService.getMaterial(materialId);
		return R.ok(material);
	}

	/**
	 * 上传运营素材
	 *
	 * @param aom
	 * @return
	 */
	@SysLog("上传运营素材")
	@PostMapping("/matUpload")
	public R<Void> matUpload(@Validated(Create.class) AdOperateMaterialVO aom) {
		try {
			List<String> fileNames = aom.getFileNames();
			List<MultipartFile> fileRaws = aom.getFileRaws();
			if (fileNames.size() != fileRaws.size()) {
				return R.failed("文件数量据与文件名称数量不匹配");
			}
			Collection<MaterialFile> materialFiles = new ArrayList<>();
			for (int i = 0; i < fileNames.size(); ++i) {
				MaterialFile materialFile = new MaterialFile();
				materialFile.setName(fileNames.get(i));
				materialFile.setFile(fileRaws.get(i));
				materialFiles.add(materialFile);
			}
			aom.setMaterialFiles(materialFiles);
			adOperateMaterialService.uploadMaterial(aom);
			return R.ok();
		} catch (Exception e) {
			log.error("上传运营素材异常", e);
			return R.failed(e.getMessage());
		}
	}

	/**
	 * 编辑素材信息
	 *
	 * @param aom
	 * @return
	 */
	@SysLog("编辑素材信息")
	@PostMapping("/update")
	public R<Void> update(@RequestBody @Validated(Update.class) AdOperateMaterialVO aom) {
		try {
			adOperateMaterialService.updateMaterial(aom);
			return R.ok();
		} catch (Exception e) {
			log.error("编辑运营素材异常", e);
			return R.failed(null, e.getMessage());
		}
	}

	/**
	 * 将Icon图推送到广点通作为品牌形象
	 *
	 * @param aom
	 * @return
	 */
	@SysLog("将Icon图推送到广点通作为品牌形象")
	@PostMapping("/pushIconAsBrand")
	public R<List<PushIconVO>> pushIconAsBrand(@RequestBody @Validated(PushIcon.class) AdOperateMaterialVO aom) throws IOException, ImageFormatException {
		Set<Long> advertiserIds = ECollectionUtil.stringToLongSet(aom.getAdvertiserIdArr());
		if (advertiserIds.isEmpty()) {
			return R.failed("投放账户不能为空");
		}
		try {
			List<PushIconVO> pushIconList = adOperateMaterialService.pushIcon(aom.getPlatformId(), aom.getMaterialId(), advertiserIds);
			if (pushIconList.stream().anyMatch(e -> !e.getSuccess())) {
				return R.failed(pushIconList, "部分或全部广告账户推送失败");
			}
			return R.ok(pushIconList);
		} catch (Exception e) {
			log.error(">>>将Icon图推送到广点通作为品牌形象:{}", e);
			return R.failed(e.getMessage());
		}
	}

	/**
	 * 下载素材
	 *
	 * @param materialId
	 * @return
	 */
	@SysLog("下载素材")
	@GetMapping("/download")
	public ResponseEntity<byte[]> download(@RequestParam Long materialId) throws IOException {
		Path filePath = adOperateMaterialService.materialPackZip(materialId);
		byte[] bytes = Files.readAllBytes(filePath);
		String fileName = materialId.toString() + ".zip";
		HttpHeaders httpHeaders = new HttpHeaders();
		ContentDisposition disposition = ContentDisposition.builder("form-data").name("attachment").filename(URLEncoder.encode(fileName, StandardCharsets.UTF_8.displayName())).build();
		httpHeaders.setContentDisposition(disposition);
		httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		return new ResponseEntity<>(bytes, httpHeaders, HttpStatus.OK);
	}

	/**
	 * 删除素材
	 *
	 * @param aom
	 * @return
	 */
	@SysLog("删除素材")
	@PostMapping("/delete")
	public R<Void> delete(@RequestBody @Validated(Delete.class) AdOperateMaterialVO aom) {
		Set<Long> materialIds = ECollectionUtil.stringToLongSet(aom.getMaterialIdArr());
		if (materialIds.isEmpty()) {
			return R.failed("请提供要删除的运营素材ID");
		}
		adOperateMaterialService.delete(materialIds);
		return R.ok();
	}

}
